package com.itheima.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 记录IP访问次数的Controller
 *
 * @author zhangbaiyan
 * @date 2024-09-28 19:41
 * @version: 1.0
 */

@RestController
@RequestMapping("/hi")
public class HelloController {

    // 使用线程安全的ConcurrentHashMap来存储IP及其访问次数
    private static final ConcurrentHashMap<String, Integer> ipVisitCount = new ConcurrentHashMap<>();

    /**
     * 访问接口，记录IP访问次数
     *
     * @param request HttpServletRequest对象，用于获取客户端IP
     * @return 当前IP的访问次数
     */
    @GetMapping
    public String visit(HttpServletRequest request) {
        String ip = getIpFromRequest(request);
        ipVisitCount.put(ip, ipVisitCount.getOrDefault(ip, 0) + 1);
        return "您的IP(" + ip + ")访问了" + ipVisitCount.get(ip) + "次";
    }

    /**
     * 从HttpServletRequest中提取客户端IP
     *
     * @param request HttpServletRequest对象
     * @return 客户端IP地址
     */

    private String getIpFromRequest(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
